package com.hsteach.service.activity;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.google.common.collect.Lists;
import com.hsteach.common.config.App;
import com.hsteach.common.config.AppConfig;
import com.hsteach.common.core.domain.model.AuthInfo;
import com.hsteach.common.exception.ServiceException;
import com.hsteach.common.utils.DateUtils;
import com.hsteach.common.utils.SecurityUtils;
import com.hsteach.common.utils.StringUtils;
import com.hsteach.dao.domain.activity.ActivityClass;
import com.hsteach.dao.mapper.activity.ActivityClassMapper;
import com.hsteach.enums.MsgTypeEnum;
import com.hsteach.framework.feign.client.xgk.dto.ret.*;
import com.hsteach.service.third.MessageService;
import com.hsteach.service.third.XgkService;
import com.hsteach.web.controller.activity.vo.EnrollTree;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.hsteach.dao.mapper.activity.ActivityEnrollMapper;
import com.hsteach.dao.domain.activity.ActivityEnroll;

/**
 * 活动报名人员Service业务层处理
 * 
 * @author fanxquer
 * @date 2023-07-11
 */
@Service
public class ActivityEnrollService
{
    @Autowired
    private ActivityEnrollMapper activityEnrollMapper;
    @Autowired
    private ActivityClassMapper activityClassMapper;

    @Autowired
    private XgkService xgkService;

    @Autowired
    private MessageService messageService;

    @Autowired
    private AppConfig appConfig;

    /**
     * 查询活动报名人员
     * 
     * @param id 活动报名人员主键
     * @return 活动报名人员
     */
    public ActivityEnroll selectTbActivityEnrollById(Long id)
    {
        return activityEnrollMapper.selectTbActivityEnrollById(id);
    }

    /**
     * 查询活动报名人员列表
     * 
     * @param activityEnroll 活动报名人员
     * @return 活动报名人员
     */
    public List<EnrollTree> selectTbActivityEnrollTree(ActivityEnroll activityEnroll)
    {
        List<ActivityEnroll> activityEnrolls = activityEnrollMapper.selectTbActivityEnrollList(activityEnroll);
        Map<String, List<ActivityEnroll>> eMap = activityEnrolls.stream().collect(Collectors.groupingBy(e -> e.getEclassId() + "," + e.getEclassName()));
        List<EnrollTree> ret = Lists.newArrayList();
        eMap.entrySet().stream().forEach(e -> {
            String[] split = e.getKey().split(",");
            EnrollTree enrollTree = new EnrollTree();
            enrollTree.setClassId(split[0]);
            enrollTree.setClassName(split[1]);
            enrollTree.setChildren(e.getValue());
            ret.add(enrollTree);
        });
        return ret;
    }

    /**
     * 对未报名的家长发送通知
     * @param msg
     * @param id
     * @return
     */
    public boolean sendMsgToNotEnroll(String msg, Long id) {
        List<PersonInfoRet> personInfoRets = selectNotEnroll(id);
        List<Guardian> parents = Lists.newArrayList();
        for (PersonInfoRet student: personInfoRets) {
            GetPersonRelationsRet personRelations = xgkService.getPersonRelations(student.getPersonId());
            parents.addAll(personRelations.getGuardianList());
        }
        List<GetParentsRet> xgkParents = xgkService.getParent(SecurityUtils.getAuthInfo().getId());
//        Map<String, String> tPersonIdMap = xgkParents.stream().flatMap(e -> e.getParents().stream())
//                .collect(Collectors.toMap(ParentEntity::getPersonId, ParentEntity::getT_personID, (v1, v2) -> v1));
        Map<String, String> tPersonIdMap = xgkParents.stream().flatMap(e -> e.getParents().stream())
                .collect(Collectors.toMap(ParentEntity::getPersonId, ParentEntity::getT_personID, (v1, v2) -> v1));
        List<String> tPersonIds = parents.stream().map(e -> tPersonIdMap.get(e.getGuardianId()))
                .filter(StringUtils::isNotEmpty).collect(Collectors.toList());
        AuthInfo authInfo = SecurityUtils.getAuthInfo();
        String appId = authInfo.getAppId();
        App app = appConfig.getConfig().get(appId);
        if (app == null) {
            throw new ServiceException("未配置消息跳转地址");
        }
        String params = "&msgId=" + id;
//            String encode = URLEncoder.encode(params, "UTF-8");
        String url = app.getRedirectUrl() + params;
        String content = "<p>" + msg + "<a href=\"" + url + "\">跳转进应用</a></p>";
        messageService.sendMsgByTPersonId(content, tPersonIds, MsgTypeEnum.ACTIVITY, "活动报名提醒");
//        tPersonIds.stream().forEach(e -> {
//            messageService.sendMsg(content, Lists.newArrayList(e), MsgTypeEnum.ACTIVITY, msg);
//        });
//        tPersonIds.stream().forEach(e -> {
//            messageService.addTodothings(msg, e, SecurityUtils.getAuthInfo().getOrganizeId(), "/activity/test", MsgTypeEnum.ACTIVITY);
//        });
        return true;
    }

    /**
     * 查询活动未报名人员列表
     *
     */
    public List<EnrollTree> selectTbActivityNotEnrollTree(Long id)
    {
        ActivityClass activityClass = new ActivityClass();
        activityClass.setActivityId(id);
        List<ActivityClass> activityClasses = activityClassMapper.selectTbActivityClassList(activityClass);
        if (activityClasses.size() == 0) {
            return Lists.newArrayList();
        }
        List<PersonInfoRet> retPersons = selectNotEnroll(id);
        List<EnrollTree> enrollTrees = buildTree(retPersons);
        for (ActivityClass aClass: activityClasses) {
            if (enrollTrees.stream().filter(e -> e.getClassId().equals(aClass.getEclassId())).collect(Collectors.toList()).size() == 0) {
                EnrollTree enrollTree = new EnrollTree();
                enrollTree.setChildren(Lists.newArrayList());
                enrollTree.setClassId(aClass.getEclassId());
                enrollTree.setClassName(aClass.getEclassName());
                enrollTrees.add(enrollTree);
            }
        }
        return enrollTrees;
    }

    public List<PersonInfoRet> selectNotEnroll(Long id) {
        ActivityClass activityClass = new ActivityClass();
        activityClass.setActivityId(id);
        List<ActivityClass> activityClasses = activityClassMapper.selectTbActivityClassList(activityClass);
        if (activityClasses.size() == 0) {
            return Lists.newArrayList();
        }
        ActivityEnroll activityEnroll = new ActivityEnroll();
        activityEnroll.setActivityId(id);
        List<ActivityEnroll> activityEnrolls = activityEnrollMapper.selectTbActivityEnrollList(activityEnroll);
        List<String> enrollIds = activityEnrolls.stream().map(ActivityEnroll::getStudentId).collect(Collectors.toList());
        List<PersonInfoRet> persons = xgkService.getStudentByClassIds(activityClasses.stream().map(ActivityClass::getEclassId).collect(Collectors.toList()));
        List<PersonInfoRet> retPersons = persons.stream().filter(e -> !enrollIds.contains(e.getPersonId())).collect(Collectors.toList());
        return retPersons;
    }

    private List<EnrollTree> buildTree(List<PersonInfoRet> retPersons) {
        Map<String, List<PersonInfoRet>> eMap = retPersons.stream().collect(Collectors.groupingBy(e -> e.getCurrentClass() + "," + e.getCurrentClassName()));
        List<EnrollTree> ret = Lists.newArrayList();
        eMap.entrySet().stream().forEach(e -> {
            String[] split = e.getKey().split(",");
            EnrollTree enrollTree = new EnrollTree();
            enrollTree.setClassId(split[0]);
            enrollTree.setClassName(split[1]);
            List<ActivityEnroll> collect = e.getValue().stream().map(k -> {
                ActivityEnroll enroll = new ActivityEnroll();
                enroll.setStudentName(k.getName());
                enroll.setStudentId(k.getPersonId());
                enroll.setSex(k.getSex());
                return enroll;
            }).collect(Collectors.toList());
            enrollTree.setChildren(collect);
            ret.add(enrollTree);
        });
        return ret;
    }

    public List<ActivityEnroll> selectTbActivityEnrollList(ActivityEnroll activityEnroll) {
        return activityEnrollMapper.selectTbActivityEnrollList(activityEnroll);
    }

    /**
     * 新增活动报名人员
     * 
     * @param activityEnroll 活动报名人员
     * @return 结果
     */
    public int insertTbActivityEnroll(ActivityEnroll activityEnroll)
    {
        activityEnroll.setCreateTime(DateUtils.getNowDate());
        return activityEnrollMapper.insertTbActivityEnroll(activityEnroll);
    }

    /**
     * 修改活动报名人员
     * 
     * @param activityEnroll 活动报名人员
     * @return 结果
     */
    public int updateTbActivityEnroll(ActivityEnroll activityEnroll)
    {
        activityEnroll.setUpdateTime(DateUtils.getNowDate());
        return activityEnrollMapper.updateTbActivityEnroll(activityEnroll);
    }

    /**
     * 批量删除活动报名人员
     * 
     * @param ids 需要删除的活动报名人员主键
     * @return 结果
     */
    public int deleteTbActivityEnrollByIds(Long[] ids)
    {
        return activityEnrollMapper.deleteTbActivityEnrollByIds(ids);
    }

    /**
     * 删除活动报名人员信息
     * 
     * @param id 活动报名人员主键
     * @return 结果
     */
    public int deleteTbActivityEnrollById(Long id)
    {
        return activityEnrollMapper.deleteTbActivityEnrollById(id);
    }
}
